package vip.xiaonuo.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.log.Log;
import cn.hutool.system.SystemUtil;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import vip.xiaonuo.core.util.HttpServletUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;

public class ZpWordUtil {

    private static final Log log = Log.get();
    // 12 代表html保存成docx
    private static final int HTML_WORD = 12;

    public static void htmlExportWord(String html, String word_name) {
        File word = convent2Word(html);  ///
        HttpServletResponse response = HttpServletUtil.getResponse();
        try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(word))) {
            String fileName = URLEncoder.encode(word_name, CharsetUtil.UTF_8);
            response.reset();
            response.setCharacterEncoding(CharsetUtil.UTF_8);
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.addHeader("Pragma", "no-cache");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            ServletOutputStream outputStream = response.getOutputStream();

            //处理文件
            int length = 0;
            byte[] bytes = new byte[4096];
            while ((length = bufferedInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            System.out.println("======下载文件失败======" + e);
            e.printStackTrace();
        }
    }

    private static File convent2Word(String str) {
        String random = RandomUtil.randomString(12);
        File html = new File(FileUtil.getTmpDir(), random + ".html");
        File word = new File(FileUtil.getTmpDir(), random + ".docx");
        FileUtil.writeString(str, html, Charset.forName(SystemUtil.get("word_charset", "GBK")));
        if (html.length() < 10) throw new RuntimeException("convent2Word error!");
        boolean b = htmlToWord(word, html);
        if (!b) throw new RuntimeException("htmlToWord error!");
        return word;
    }


    public static boolean htmlToWord(File wordFile, File htmlFile) {
        ActiveXComponent app = new ActiveXComponent("Word.Application"); // 启动word
        try {
            app.setProperty("Visible", new Variant(false));
            Dispatch wordDoc = app.getProperty("Documents").toDispatch();
            wordDoc = Dispatch.invoke(wordDoc, "Add", Dispatch.Method, new Object[0], new int[1]).toDispatch();
            Dispatch.invoke(app.getProperty("Selection").toDispatch(), "InsertFile", Dispatch.Method,
                    new Object[]{htmlFile.getAbsolutePath(), "", new Variant(false), new Variant(false), new Variant(false)},
                    new int[3]);
            Dispatch.invoke(wordDoc, "SaveAs", Dispatch.Method, new Object[]{wordFile.getAbsolutePath(), new Variant(HTML_WORD)},
                    new int[1]);
            Dispatch.call(wordDoc, "Close", new Variant(false));
            return wordFile.exists();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            app.invoke("Quit", new Variant[]{});
        }
        return false;
    }


//    public static void exportWordWithStream(String wordName, File template, Map<String, Object> data) {
//        try {
//            HttpServletResponse response = HttpServletUtil.getResponse();
//            String fileName = URLEncoder.encode(wordName, CharsetUtil.UTF_8);
//            response.reset();
//            response.setCharacterEncoding(CharsetUtil.UTF_8);
//            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
//            response.setContentType("application/octet-stream;charset=UTF-8");
//            ServletOutputStream outputStream = response.getOutputStream();
//            XWPFDocument word = WordExportUtil.exportWord07(template.getAbsolutePath(), data);
//            word.write(outputStream);
//            outputStream.close();
//        } catch (Exception e) {
//            log.error(">>> 导出数据异常：{}", e.getMessage());
//            e.printStackTrace();
//        }
//    }


}
